var express = require('express')
var router = express.Router()
const { getAll, getOne, exec } = require('../db')
var jwt = require('jsonwebtoken')

const secretKey = 'secret'

// 新增用户(注册)
/**
 * /register
 * body{
 * username, password
 * }
 */
router.post('/', async function (req, res, next) {
  const { username, password, truename, telnumber } = req.body
  let sql_get = `select * from gg_user where user_username='${username}'`
  // 查询是否存在该用户名
  const data_get = await getOne(sql_get)
  //console.log(data_get)//没有查询到时为null
  if (data_get) {
    res.send({
      code: 101,
      message: '该用户名已被占用',
      result: username,
    })
  } else {
    let sql_post = `insert into gg_user (user_username,user_password,use_truename,user_tel) values ('${username}','${password}','${truename}','${telnumber}')`
    const data_post = await exec(sql_post)
    // console.log(data_post)
    // console.log(data_post.insertId)
    if (data_post) {
      res.send({
        code: 0,
        message: '用户注册成功',
        results: {
          use_id: data_post.insertId,
          user_username: username,
        },
      })
    } else {
      res.send({
        code: 11,
        message: '用户注册失败',
        result: '',
      })
    }
  }
})

module.exports = router
